<?php namespace App\Admin\Access\Role;

use App\Core\Repository\Repository as BaseRepository;
use Auth;

class Repository extends BaseRepository {
    
    public function model(){
        return new Model();
    }
    
    public function getTree($roles){
		$rolesTree = [];
		foreach ($roles as $value){
			$value = $value->toArray();
			$value['sub'] = [];
			$value['parent_id_code'] = $this->getParentIdCode($value['parent_id']);
			$value['role_id_code'] = $this->getRoleIdCode($value['role_id']);
            $roleId = $value['role_id_code'];
			$roleIdArr = [];
            for($i = 0;$i<strlen($roleId)/2;$i++){
                $roleIdArr[] = substr($roleId, $i*2, 2);
            }
			if($roleIdArr){
				eval('$rolesTree[\''.implode('\'][\'sub\'][\'', $roleIdArr).'\'] = $value;');
			}
		}
		return $rolesTree;
    }
    
    //获取role_id_code 为了解决不同权限级别的用户在分配了角色管理权限之后只能管理自己职责范围之内的角色时角色树的截取问题
	public function getRoleIdCode($roleId){
		$user = Auth::user();
		$userRoleIdLen = $user->isAdmin() ? 0 : strlen($user->role->role_id);
		return substr($roleId, $userRoleIdLen);
	}
	
	//获取parent_id_code
	public function getParentIdCode($parentId){
		$user = Auth::user();
		$userRoleIdLen = $user->isAdmin() ? 0 : strlen($user->role->role_id);
		$parent_id_sub = substr($parentId, $userRoleIdLen);
		return $parent_id_sub ? $parent_id_sub : '0';
	}
    
    //获取主键
	public function getNextId($parentId){
        $this->resetQuery()->getQuery()->where('parent_id', '=', $parentId)->orderBy('role_id', 'desc');
		$role = $this->first();
		if(!empty($role)){
			$roleBigId = $role->role_id;
			$last = (int)substr($roleBigId, -2) + 1;
			if(strlen($roleBigId) > 2){
				return substr($roleBigId, 0, -2).$last;
			}else{
				return $last;
			}
		}else{
			if($parentId == 0){
				return '10';
			}else{
				return $parentId.'10';
			}
		}
	}
    
    //获取当前用户的角色
	public function getMyRoles(){
        return $this->resetQuery()->resetCriteria()->addCriteria(new Criterias\HasPermission())->all();
	}
}